package yhao.demo.autocode.core.feignmapper;

import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.AnnotationMetadataReadingVisitor;
import org.springframework.core.type.classreading.MetadataReader;

import java.util.ArrayList;
import java.util.List;

public class ClassPathScanner extends
        ClassPathScanningCandidateComponentProvider {
	//懒汉单例
	private static ClassPathScanner scanner = new ClassPathScanner(true);
	public static ClassPathScanner getInstance(){
		return scanner;
	}

	private ClassPathScanner(boolean useDefaultFilters) {
		super(useDefaultFilters);
	}

	/**
	 * 类路径Bean定义扫描器扫描给定包及其子包，查找是否包含某注解
	 */
	public List<FeignDefinition> doScan(String basePackage){
		// 遍历扫描所有给定的包
		return findFeignDef(basePackage);
	}

	private List<FeignDefinition> findFeignDef(String basePackage) {
		List<FeignDefinition> result = new ArrayList<>();
		try {
			String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
					resolveBasePackage(basePackage) + '/' + "**/*.class";
			Resource[] resources = ((ResourcePatternResolver)this.getResourceLoader()).getResources(packageSearchPath);
			for (Resource resource : resources) {
				if (resource.isReadable()) {
					try {
						MetadataReader metadataReader = this.getMetadataReaderFactory().getMetadataReader(resource);
						AnnotationMetadataReadingVisitor classMeta = (AnnotationMetadataReadingVisitor)metadataReader.getClassMetadata();
						FeignDefinition def = new FeignDefinition(classMeta);
						if(def.getMethodDefinitions().size()>0){
							result.add(def);
						}
					}catch (Exception e){}
				}
			}
		}catch (Exception e){}
		return result;
	}
}
